import numpy as np
import matplotlib.pyplot as plt
import matplotlib.font_manager as fm

def get_available_chinese_fonts():
    """获取系统中可用的中文字体列表"""
    chinese_fonts = []
    for font in fm.fontManager.ttflist:
        try:
            font_name = font.name
            if 'hei' in font_name.lower() or 'song' in font_name.lower() or \
               'kai' in font_name.lower() or 'fang' in font_name.lower():
                chinese_fonts.append(font_name)
        except:
            continue
    return chinese_fonts

# 获取可用中文字体
available_fonts = get_available_chinese_fonts()

# 设置字体配置
if available_fonts:
    plt.rcParams["font.family"] = available_fonts[0]
    print(f"已成功设置中文字体: {available_fonts[0]}")
else:
    print("未找到可用的中文字体，将使用默认字体")
    plt.rcParams["font.family"] = ["SimHei", "WenQuanYi Micro Hei", "Heiti TC"]

plt.rcParams['axes.unicode_minus'] = False  # 正确显示负号

def plot_vortex_system(vortices, a=1.0, U=1.0):
    """
    多涡系统流场可视化函数
    
    参数:
    vortices: 涡的列表，每个元素为(x坐标, y坐标, 环量Γ)
    a: 圆柱半径
    U: 来流速度
    """
    # 生成计算网格
    x = np.linspace(-3*a, 3*a, 300)
    y = np.linspace(-3*a, 3*a, 300)
    X, Y = np.meshgrid(x, y)
    Z = X + 1j*Y
    
    # 计算复势Φ(z)
    F = U * (Z + a**2 / Z)  # 圆柱绕流基本复势
    for (x_v, y_v, gamma) in vortices:
        z_v = x_v + 1j*y_v
        z_mirror = a**2 / np.conj(z_v)  # 计算镜像涡位置
        term = (Z - z_v) / (Z - z_mirror) * (a / abs(z_v))
        F += 1j * gamma / (2 * np.pi) * np.log(term)
    
    # 提取流函数ψ=Im(Φ)
    psi = np.imag(F)
    
    # 绘制流线图
    plt.figure(figsize=(10, 8))
    cntr = plt.contour(X, Y, psi, levels=30, colors='k', linewidths=1)
    plt.clabel(cntr, inline=True, fontsize=8)  # 添加流线数值标签
    
    # 标注实际涡（红点）
    actual_vortices_x = [v[0] for v in vortices]
    actual_vortices_y = [v[1] for v in vortices]
    plt.scatter(actual_vortices_x, actual_vortices_y, c='red', 
                marker='o', s=100, label='实际涡(O)')
    
    # 标注镜像涡（蓝叉）
    mirror_vortices = []
    for (x_v, y_v, _) in vortices:
        z_v = x_v + 1j*y_v
        z_mirror = a**2 / np.conj(z_v)
        mirror_vortices.append((z_mirror.real, z_mirror.imag))
    mirror_vortices_x = [v[0] for v in mirror_vortices]
    mirror_vortices_y = [v[1] for v in mirror_vortices]
    plt.scatter(mirror_vortices_x, mirror_vortices_y, c='blue', 
                marker='x', s=100, label='镜像涡(X)')
    
    # 绘制圆柱边界
    theta = np.linspace(0, 2*np.pi, 100)
    circle_x = a * np.cos(theta)
    circle_y = a * np.sin(theta)
    plt.plot(circle_x, circle_y, 'g--', linewidth=2, label=f'圆柱边界(|z|={a})')
    
    # 设置图像属性
    plt.xlim(-3*a, 3*a)
    plt.ylim(-3*a, 3*a)
    plt.xlabel('实部(x)', fontsize=12)
    plt.ylabel('虚部(y)', fontsize=12)
    plt.title('多涡系统流场可视化', fontsize=14)
    plt.grid(True, linestyle='--', alpha=0.7)
    plt.legend(loc='best', fontsize=10)
    plt.axis('equal')  # 保证x和y轴比例相同
    
    # 显示图像
    plt.tight_layout()
    plt.show()

# 示例：双涡系统可视化
if __name__ == "__main__":
    # 定义双涡系统参数：(x, y, Γ)
    vortices = [(2.0, 0.0, 2*np.pi), (-2.0, 0.0, -2*np.pi)]
    plot_vortex_system(vortices, a=1.0, U=1.0)